﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Bifrost;
using System.Xml;
using Bifrost.WcfSvr;

namespace CLIENT_EMR.TEMPLATE
{
    public partial class frmDocWebShowSet : DevComponents.DotNetBar.Metro.MetroForm
    {
        //private DataTable T_DOC_WEBSHOW;
        //private DataTable T_DOC_WEBSHOW_PARTS;
        //private DataTable T_DOC_WEBSHOW_PDIV;

        public frmDocWebShowSet()
        {
            InitializeComponent();           
        }

        private void frmDocWebShowSet_Load(object sender, EventArgs e)
        {
            GetWebTexts();
            ShearchAllTempLate("");
            
        }

        /// <summary>
        /// 获取Web显示文书一级
        /// </summary>
        private void setAllWebTextShow()
        {
            string sql="select b.id,b.textname from t_text b where b.id in (select distinct a.text_type " +
                       "from t_tempplate a where a.text_type is not null) and b.enable_flag='Y' order by b.isbelongtotype,b.shownum asc";
            DataSet ds = App.wc.GetDataSet(sql);
            List<string> sqls = new List<string>();
            sqls.Add("delete from t_doc_webshow");
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                string tid=ds.Tables[0].Rows[i]["id"].ToString();
                string textname=ds.Tables[0].Rows[i]["textname"].ToString();
                sqls.Add("insert into t_doc_webshow(tid,docname,shownum)values(" + tid + ",'" + textname + "'," + tid + ")");
            }

            if (App.ExecuteBatch(sqls.ToArray()) > 0)
            {
                App.Msg("操作已经成功！");
                GetWebTexts();
                
            }
            else
            {
                App.MsgErr("操作失败！");
            }

        }

        private void getDivsByTid(string tid)
        {
            //子项节点                
            //string sql = "select a.divid,divname from t_doc_webshow_pdiv a where ptid=" + ptid + "";

            string sql = "select divid,divname,bb.textname,text_type,tid from t_doc_webshow_pdiv aa  inner  join t_text bb on aa.tid=bb.id where aa.tid=" + tid + "";

            DataTable temptable = App.wc.GetDataSet(sql).Tables[0];
            //DataTable temptable = ComHelp.ToDataTable(rows);
            if (temptable != null)
            {
                dataGridViewX1.DataSource = temptable.DefaultView;
                dataGridViewX1.Columns["divid"].HeaderText = "DIV主键";
                dataGridViewX1.Columns["divname"].HeaderText = "DIV名称";
                dataGridViewX1.Columns["textname"].HeaderText = "文书类型";
                dataGridViewX1.Columns["text_type"].Visible = false;
                dataGridViewX1.Columns["tid"].Visible = false;
                dataGridViewX1.AutoResizeColumns();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void GetWebTexts()
        {
            //string[] sqls = new string[3];
            //sqls[0] = "select * from T_DOC_WEBSHOW";
            //sqls[1] = "select * from T_DOC_WEBSHOW_PARTS";
            //sqls[2] = "select * from T_DOC_WEBSHOW_PDIV";

            trvWebShow.Nodes.Clear();

            Class_Table[] tablesqls=new Class_Table[2];
            tablesqls[0]=new Class_Table();
            tablesqls[0].Sql="select * from T_DOC_WEBSHOW order by shownum asc";
            tablesqls[0].Tablename="T_DOC_WEBSHOW";
           
            tablesqls[1] = new Class_Table();
            tablesqls[1].Sql = "select * from T_DOC_WEBSHOW_PDIV";
            tablesqls[1].Tablename = "T_DOC_WEBSHOW_PDIV";

            DataSet ds = App.wc.GetDataSets(tablesqls);

            DataTable T_DOC_WEBSHOW=ds.Tables["T_DOC_WEBSHOW"];       
            DataTable T_DOC_WEBSHOW_PDIV = ds.Tables["T_DOC_WEBSHOW_PDIV"];

           
            for (int i = 0; i < T_DOC_WEBSHOW.Rows.Count; i++)
            {
                TreeNode pnode = new TreeNode();
                pnode.Name = T_DOC_WEBSHOW.Rows[i]["TID"].ToString();
                pnode.Text = T_DOC_WEBSHOW.Rows[i]["DOCNAME"].ToString();
                DataRow[] rows = T_DOC_WEBSHOW_PDIV.Select("TID='" + pnode.Name + "'");
                pnode.ImageIndex = 13;
                pnode.SelectedImageIndex = 13;
                pnode.Tag = "webshow";
                if (rows.Length > 0)
                {
                    pnode.ImageIndex = 7;
                    pnode.SelectedImageIndex = 7;
                }
                trvWebShow.Nodes.Add(pnode);
            }
            trvWebShow.ExpandAll();
        }

        /// <summary>
        /// 获取模版文书类型
        /// </summary>
        /// <param name="TextName"></param>
        private void ShearchAllTempLate(string TextName)
        {
            string sql="select b.id,b.textname from t_text b where b.id in (select distinct a.text_type "+
                       "from t_tempplate a where a.text_type is not null) and textname like '%"+TextName+
                       "%' and b.enable_flag='Y' ";

            DataSet dsText = App.wc.GetDataSet(sql);
            trvTemplate.Nodes.Clear();
            for (int i = 0; i < dsText.Tables[0].Rows.Count; i++)
            {
                TreeNode tn = new TreeNode();
                tn.Name = dsText.Tables[0].Rows[i]["id"].ToString();
                tn.Text = dsText.Tables[0].Rows[i]["textname"].ToString();
                tn.ImageIndex = 12;
                tn.SelectedImageIndex = 12;
                trvTemplate.Nodes.Add(tn);
            }            
        }

        /// <summary>
        /// 根据模版类型获取模版集合
        /// </summary>
        /// <param name="tnode"></param>
        private void GetTemplatesByTextId(TreeNode tnode)
        {
            string sql = "select cc.tid,cc.tname from t_tempplate cc where cc.text_type='" + tnode.Name + "'";
            DataSet dsTemplate = App.wc.GetDataSet(sql);
            tnode.Nodes.Clear();
            for (int i = 0; i < dsTemplate.Tables[0].Rows.Count; i++)
            {
                TreeNode tn = new TreeNode();
                tn.Name = dsTemplate.Tables[0].Rows[i]["tid"].ToString();
                tn.Text = dsTemplate.Tables[0].Rows[i]["tname"].ToString();
                tn.Tag = tnode.Name;               
                tn.ImageIndex = 6;
                tn.SelectedImageIndex = 6;
                tnode.Nodes.Add(tn);
            }
            tnode.ExpandAll();
        }

        /// <summary>
        /// 根据模版id获取Div级的标签
        /// </summary>
        /// <param name="templateid"></param>
        private void GetDivsByTemplate(string templateid,string textid)
        {
            string sql = "select dd.content from t_tempplate_cont dd where dd.tid=" + templateid + "";
            DataSet ds = App.wc.GetDataSet(sql);
            string Content = ds.Tables[0].Rows[0][0].ToString();
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(Content);

            XmlNodeList bodynodes = doc.GetElementsByTagName("body");
            trvDivs.Nodes.Clear();
            if (bodynodes.Count > 0)
            {
                foreach (XmlNode tnode in bodynodes[0].ChildNodes)
                {
                    if (tnode.Name.ToLower() == "div")
                    {                       
                        TreeNode tn = new TreeNode();
                        tn.Name = tnode.Attributes["id"].Value;
                        tn.Text = tnode.Attributes["title"].Value;
                        tn.Tag = textid;
                        trvDivs.Nodes.Add(tn);
                    }
                }
            }            
        }


        private void toolStripButtonAdd_Click(object sender, EventArgs e)
        {
            H1:
            frmWebShowItem fc = new frmWebShowItem("",null);
            fc.ShowDialog();
            if (frmWebShowItem.ID != "")
            {
                TreeNode tn = new TreeNode();
                tn.Name = frmWebShowItem.ID;
                tn.Text = frmWebShowItem.TName;
                tn.Tag = "webshow";
                trvWebShow.Nodes.Add(tn);
                trvWebShow.ExpandAll();
                string sql = "insert into T_DOC_WEBSHOW(tid,Docname,SHOWNUM)values(" + tn.Name + ",'" + tn.Text + "'," + tn.Name + ")";
                App.wc.ExecuteSQL(sql);

                goto H1;
            }

        }

        private void toolStripButtonAddChild_Click(object sender, EventArgs e)
        {
           
            if (trvWebShow.SelectedNode.Tag.ToString() == "webshow")
            {
                H1:
                //当前为文书级节点
                frmWebShowItem fc = new frmWebShowItem("", trvWebShow.SelectedNode);
                fc.ShowDialog();
                if (frmWebShowItem.ID != "")
                {
                    TreeNode tn = new TreeNode();
                    tn.Name = frmWebShowItem.ID;
                    tn.Text = frmWebShowItem.TName;
                    tn.Tag = "webshow_parts";
                    tn.ImageIndex = 7;
                    tn.SelectedImageIndex = 7;
                    trvWebShow.SelectedNode.Nodes.Add(tn);
                    trvWebShow.ExpandAll();
                    string sql = "insert into T_DOC_WEBSHOW_PARTS(ptid,tid,PARTS_NAME,Shownum)values(" +
                                   tn.Name + "," + trvWebShow.SelectedNode.Name + ",'" +
                                   tn.Text + "'," + tn.Name + ")";
                    App.wc.ExecuteSQL(sql);
                    goto H1;
                }
            }
            else if (trvWebShow.SelectedNode.Tag.ToString() == "webshow_parts")
            {
                 H1:
                //当前为文书子节点
                frmWebShowItem fc = new frmWebShowItem("", trvWebShow.SelectedNode.Parent);
                fc.ShowDialog();
                if (frmWebShowItem.ID != "")
                {
                    TreeNode tn = new TreeNode();
                    tn.Name = frmWebShowItem.ID;
                    tn.Text = frmWebShowItem.TName;
                    tn.Tag = "webshow_parts";
                    tn.ImageIndex = 7;
                    tn.SelectedImageIndex = 7;                  
                    trvWebShow.SelectedNode.Parent.Nodes.Add(tn);
                    trvWebShow.ExpandAll();
                    string sql = "insert into T_DOC_WEBSHOW_PARTS(ptid,tid,PARTS_NAME,Shownum)values(" +
                                   tn.Name + "," + trvWebShow.SelectedNode.Parent.Name + ",'" +
                                   tn.Text + "'," + tn.Name + ")";
                    App.wc.ExecuteSQL(sql);
                    goto H1;
                }
            }
        }

        private void txtSearchName_TextChanged(object sender, EventArgs e)
        {
            ShearchAllTempLate(txtSearchName.Text);
        }

        private void trvTemplate_DoubleClick(object sender, EventArgs e)
        {
            if (trvTemplate.SelectedNode.Parent == null)
                GetTemplatesByTextId(trvTemplate.SelectedNode);
        }

        private void trvTemplate_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (trvTemplate.SelectedNode.Parent != null)
            {
                //模版一级节点
                GetDivsByTemplate(trvTemplate.SelectedNode.Name, trvTemplate.SelectedNode.Tag.ToString());
            }
        }

        private void toolStripButtonDel_Click(object sender, EventArgs e)
        {

            if (trvWebShow.SelectedNode.Tag.ToString() == "webshow")
            {
                //顶级节点
                string sqldel = "delete from T_DOC_WEBSHOW where tid=" + 
                                    trvTemplate.SelectedNode.Name + "";
                if (trvWebShow.SelectedNode.Nodes.Count > 0)
                {
                    if (App.Ask("已经存在了子项,如果删除的话将清除该节点的所有数据，确定要删除吗?"))
                    {
                        string[] sqls = new string[1];
                        sqls[0] = "delete from T_DOC_WEBSHOW_PDIV a where a.tid=" + trvWebShow.SelectedNode.Name + "";                       
                        sqls[1] = "delete from T_DOC_WEBSHOW where tid=" + trvWebShow.SelectedNode.Name + "";
                        if (App.wc.ExecuteBatch(sqls) > 0)
                        {
                            trvWebShow.SelectedNode.Remove();
                        }
                    }
                }                                  
            }           
        }

        private void trvWebShow_AfterSelect(object sender, TreeViewEventArgs e)
        {           
           getDivsByTid(trvWebShow.SelectedNode.Name);           
        }

        private void trvDivs_AfterSelect(object sender, TreeViewEventArgs e)
        {

        }

        private void trvDivs_DoubleClick(object sender, EventArgs e)
        {           
            string tid = trvWebShow.SelectedNode.Name;
            string divdid = trvDivs.SelectedNode.Name;
            string divname = trvDivs.SelectedNode.Text;
            string textid = trvDivs.SelectedNode.Tag.ToString();
            string sql = "insert into t_doc_webshow_pdiv(templateid,divid,divname,text_type,tid)values(0,'" +
                             divdid + "','" + divname + "'," + textid + "," + tid + ")";
            if (App.ExecuteSQL(sql) == 0)
            {
                App.MsgErr("操作未成功！");
            }               
           getDivsByTid(trvWebShow.SelectedNode.Name);             
        }

        private void toolStripButtonSetAllText_Click(object sender, EventArgs e)
        {
            setAllWebTextShow();
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            try
            {
                
                string divid = dataGridViewX1["divid", dataGridViewX1.CurrentRow.Index].Value.ToString();
                string tid = dataGridViewX1["tid", dataGridViewX1.CurrentRow.Index].Value.ToString();
                string sql = "delete from t_doc_webshow_pdiv a where a.divid='" + divid + "' and a.tid=" + tid + "";
                if (App.Ask("是否要删除\"" + divid + "\"的div记录？？"))
                {
                    if (App.ExecuteSQL(sql) > 0)
                    {
                        App.Msg("操作成功！");
                        getDivsByTid(tid);
                    }
                }
            }
            catch(Exception ex)
            {
                App.MsgErr("操作失败！错误原因："+ex.Message);
            }
        }

        private void toolStripButtonUp_Click(object sender, EventArgs e)
        {
           
            if (trvWebShow.SelectedNode != null)
            {
                if (trvWebShow.SelectedNode.PrevNode != null)
                {
                   

                    string prevnodename = trvWebShow.SelectedNode.PrevNode.Name;
                    string selectnodename = trvWebShow.SelectedNode.Name;

                    string[] sqls = new string[2];
                    sqls[0] = "update t_doc_webshow set shownum=" + prevnodename + " where tid=" + selectnodename + "";
                    sqls[1] = "update t_doc_webshow set shownum=" + selectnodename + " where tid=" + prevnodename + "";
                   
                    App.wc.ExecuteBatch(sqls);
                    App.TrvNodeMovUp(trvWebShow.SelectedNode, trvWebShow);
                }

            }
        }

        private void toolStripButtonDown_Click(object sender, EventArgs e)
        {

            App.TrvNodeMovDown(trvWebShow.SelectedNode, trvWebShow);
            if (trvWebShow.SelectedNode != null)
            {
                if (trvWebShow.SelectedNode.NextNode != null)
                {
                    string nexnodename = trvWebShow.SelectedNode.NextNode.Name;
                    string selectnodename = trvWebShow.SelectedNode.Name;


                    string[] sqls = new string[2];
                    sqls[0] = "update t_doc_webshow set shownum=" + nexnodename + " where tid=" + selectnodename + "";
                    sqls[1] = "update t_doc_webshow set shownum=" + selectnodename + " where tid=" + nexnodename + "";
                    App.wc.ExecuteBatch(sqls);

                    //Class_Text temp1 = (Class_Text)trvDictionary.SelectedNode.NextNode.Tag;
                    //Class_Text temp2 = (Class_Text)trvDictionary.SelectedNode.Tag;
                    //App.wc.ChangeTextShowNum(temp1.Shownum, temp1.Id.ToString(), temp2.Shownum, temp2.Id.ToString());
                }
            }
        }
    }
}
